package com.far.permisions.context;

import cn.hutool.core.collection.CollectionUtil;
import com.far.permisions.manager.ExclusionsManager;
import com.far.permissions.enums.Strategy;

import java.util.HashSet;
import java.util.Set;

public class DpContext {
    private final static ThreadLocal<DpContext> LOCAL = new ThreadLocal<>();

    private Strategy strategy;
    private final ExclusionsManager exclusionsManager = new ExclusionsManager();

    public DpContext(Set<String> exclusions, Strategy strategy) {
        exclusionsManager.addAll(exclusions);
        this.strategy = strategy;
    }

    public DpContext(Strategy strategy) {
        this.strategy = strategy;
    }

    public Set<String> getExclusions() {
        return exclusionsManager.getExclusions();
    }

    public void setExclusions(Set<String> exclusions) {
        exclusionsManager.addAll(exclusions);
    }

    public Strategy getStrategy() {
        return strategy;
    }

    public static DpContext register(Set<String> exclusion) {
        Strategy strategy = CollectionUtil.isEmpty(exclusion) ? Strategy.GLOBAL : Strategy.DESIGNATED;
        DpContext dpContext = new DpContext(exclusion, strategy);
        LOCAL.set(dpContext);
        return dpContext;
    }

    public static DpContext register() {
        return register(null);
    }

    public DpContext addExclusion(String exclusion) {
        exclusionsManager.add(exclusion);
        strategy = Strategy.DESIGNATED;
        return this;
    }

    public static DpContext get() {
        DpContext dpContext = LOCAL.get();
        if (dpContext == null) {
            dpContext = new DpContext(Strategy.NONE);
            LOCAL.set(dpContext);
        }
        return dpContext;
    }

    public static void clear() {
        LOCAL.remove();
    }
}
